const { QueryTypes, Op } = require("sequelize");
const sequelize = require("../sequelize");
const productModel = require("../sequelize/product");
const productLabelModel = require("../sequelize/productLabel");
const productImageModel = require("../sequelize/productImage");
const shopModel = require("../sequelize/shop");
const typeModel = require("../sequelize/type");
const { uploadFile } = require("../utils/utils");

class Service {
    async list(query) {
        const where = {};
        if (query.typeId) {
            where.typeId = query.typeId;
        }
        return {
            code: 200,
            message: "ok",
            result: await productModel.findAll({
                where,
                include: [
                    {
                        model: productImageModel,
                    },
                    {
                        model: productLabelModel,
                    },
                    {
                        model: typeModel,
                    },
                ],
            }),
        };
    }

    async add(body) {
        await productModel.create(body);
        return {
            code: 200,
            message: "ok",
            result: body,
        };
    }

    async update(body) {
        await productModel.update(body, {
            where: {
                id: body.id,
            },
        });
        return {
            code: 200,
            message: "ok",
            result: body,
        };
    }

    async del(body) {
        await productModel.destroy({
            where: {
                id: body.id,
            },
        });
        return {
            code: 200,
            message: "ok",
            result: body,
        };
    }

    async addLabel(body) {
        await productLabelModel.create(body);
        return {
            code: 200,
            message: "ok",
            result: body,
        };
    }

    async delLabel(body) {
        await productLabelModel.destroy({
            where: {
                id: body.id,
            },
        });
        return {
            code: 200,
            message: "ok",
            result: body,
        };
    }

    async uploadImage(req) {
        const fileInfo = await uploadFile(req, "/public/");
        const id = req.url.split("?")[1].split("=")[1];
        if (id) {
            await productImageModel.create({
                url: fileInfo,
                productId: id,
            });
        }
        return {
            code: 200,
            message: "ok",
            result: {
                url: fileInfo,
            },
        };
    }

    /*
        假设当前 经度为：118.356734 纬度为：21.785367
        SELECT
          *,(
            6371 * acos (
              cos ( radians(21.785367) )
              * cos( radians( lat ) )
              * cos( radians( lng ) - radians(118.356734) )
              + sin ( radians(21.785367) )
              * sin( radians( lat ) )
            )
          ) AS distance  //距离
        FROM t_shop
        HAVING distance < 2  //筛选距离小于2km的商家(可不写)，如果没查到数据就是没有小于2km的商家
        ORDER BY distance  //根据距离远近来排序 默认升序 （可不写）
        LIMIT 0 , 20;  //显示前20条数据（可不写）
     */
    async getProductByPosition(query) {
        const shops = await sequelize.query(
            `
                SELECT
                    *,(
                        6371 * acos (
                                    cos ( radians(${query.lat}) )
                                    * cos( radians( lat ) )
                                    * cos( radians( lng ) - radians(${query.lng}) )
                                + sin ( radians(${query.lat}) )
                                        * sin( radians( lat ) )
                        )
                    ) AS distance
                FROM shops
                HAVING distance < 1000000
                ORDER BY distance
                LIMIT 0 , 20;
            `,
            { type: QueryTypes.SELECT }
        );
        const list = [];
        // for (let i = 0; i < shops.length; i++) {
        // 	const shop = shops[i];

        // 	let where = {
        // 		shopId: shop.id,
        // 	};
        // 	if (query.keyword) {
        // 		where = {
        // 			...where,
        // 			title: {
        // 				[Op.like]: "%" + query.keyword,
        // 			},
        // 		};
        // 	}

        // 	const products = await productModel.findAll({
        // 		where,
        // 		include: [
        // 			{
        // 				model: productImageModel,
        // 			},
        // 			{
        // 				model: productLabelModel,
        // 			},
        // 		],
        // 	});
        // 	list.push(
        // 		products.map(ele => {
        // 			return {
        // 				...ele.dataValues,
        // 				shop: {
        // 					...shop,
        // 					distance: shop.distance.toFixed(1),
        // 				},
        // 			};
        // 		})
        // 	);
        // }
        if (query.keyword) {
            where = {
                ...where,
                title: {
                    [Op.like]: "%" + query.keyword,
                },
            };
        }

        const products = await productModel.findAll({
            where,
            include: [
                {
                    model: productImageModel,
                },
                {
                    model: productLabelModel,
                },
                {
                    model: typeModel,
                },
            ],
        });
        list.push(products);
        return {
            code: 200,
            message: "ok",
            result: list.flat(),
        };
    }

    async getProductByShopId(query) {
        const products = await productModel.findAll({
            where: {
                typeId: query.id,
            },
            include: [
                {
                    model: productImageModel,
                },
                {
                    model: productLabelModel,
                },
                {
                    model: typeModel,
                },
            ],
        });
        return {
            code: 200,
            message: "ok",
            result: products,
        };
    }

    async getProductById(query) {
        const product = await productModel.findOne({
            where: {
                id: query.id,
            },
            include: [
                {
                    model: productImageModel,
                },
                {
                    model: productLabelModel,
                },
                {
                    model: typeModel,
                },
            ],
        });
        return {
            code: 200,
            message: "ok",
            result: product,
        };
    }
}

module.exports = new Service();
